/**
 * 日常任务列表
 * @author truexin
 * @date   16/07/06
 */

import PullRefresh from '../components/mui/PullRefresh.js';
import NoData from '../components/NoData.js';

(function (lf, r) {
    let RC = r.createClass,
        ajax = lf.utils.ajax,
        getUrlParam = lf.utils.getUrlParam,
        doAction = lf.bridgeJs.doAction;
    
    const TYPE = getUrlParam('type'),
        CONFIRM = 'confirm',
        FEEDBACK = 'feedback',
        CHECK = 'check',
        BACK = 'back',
        HELP = 'help',
        COMPLETE = 'complete',
        DELETE = 'delete',
        DISPATCH = 'dispatch';
    
    const ALL = 'all',
        MONTH = 'month',
        WEEK = 'week',
        MARK = 'mark';
    
    let range = lf.utils.getUrlParam('flag', location.search);
    
    let counts = []; //由于已完成页面下拉出现数字为0,所以写在这里
    
    let Header = r.createClass({
        getInitialState: function () {
            return {
                headers: [
                    {
                        title: '全部',
                        range: ALL
                    },
                    {
                        title: '本月',
                        range: MONTH
                    },
                    {
                        title: '本周',
                        range: WEEK
                    },
                    // {
                    //     title: '已标记',
                    //     range: MARK
                    // }
                ],
                counts: [],
            }
        },
        componentDidMount: function () {
            let $links = $('.header a'),
                me = this;
            
            if (!$links.length) return;
            
            //默认第一个点中
            $links.eq(0).addClass('active');
            
            //点击
            $links.each(function () {
                $(this).on('tap', function () {
                    //切换样式,
                    $(this).addClass('active')
                    .siblings().removeClass('active');
                    
                    range = $(this).data('range');
                    // debugAlert(range)
                    me.props.getList(me.props.user, 1, false);//TODO 这里需要修改
                    
                }.bind(this));
                
            });
        },
        render: function () {
            let me = this;
            let headers = this.state.headers.map(function (data, i) {
                return (
                    <a key={'head-'+i} data-range={data.range} className="item" href="javascript:;">
                        <p>{me.props.counts[i] || 0}</p>
                        <p className="bold">{data.title}</p>
                        <div className="rectangle"></div>
                    </a>
                );
            });
            let addClass = '';
            if (me.props.taskType == '04') {
                addClass = '';
            } else {
                addClass = 'eleHide'
            }
            
            return (
                <div className={"header "+ addClass}>
                    <div className="item-row">
                        {headers}
                    </div>
                    <div className="split-line"></div>
                </div>
            )
        },
    });
    
    
    let WorkList = RC({
        render: function () {
            let noData = this.props.noData;
            let work_list = this.props.info.map(function (info, i) {
                return (
                    <List key={'list'+i} info={info} taskId={info.id}/>
                )
            })
            if (noData && TYPE == CONFIRM) {
                let noData = {
                    span_text: '任务已经处理完啦',
                };
                return <NoData data={noData}/>
            } else if (noData && TYPE == FEEDBACK) {
                let noData = {
                    span_text: '任务已经处理完啦',
                };
                return <NoData data={noData}/>
            } else if (noData && TYPE == CHECK) {
                let noData = {
                    span_text: '没有需要您审核的任务哦',
                };
                return <NoData data={noData}/>
            } else if (noData && TYPE == BACK) {
                let noData = {
                    span_text: '暂无可撤回的任务',
                };
                return <NoData data={noData}/>
            } else if (noData && TYPE == HELP) {
                let noData = {
                    span_text: '没有需要您协办的任务哦',
                };
                return <NoData data={noData}/>
            } else if (noData && TYPE == DISPATCH) {
                let noData = {
                    span_text: '您还没有派遣任务',
                    btn_text: '立即新建',
                    page_url: 'daily-work-add.html',
                    page_title: '新建任务',
                };
                return <NoData data={noData}/>
            } else if (noData && TYPE == COMPLETE) {
                let noData = {
                    span_text: '还没有完成的任务哦',
                };
                return <NoData data={noData}/>
            } else {
                return (
                    <ul className="body mui-table-view lf-list">
                        {work_list}
                    </ul>
                )
            }
        }
    })
    
    let List = RC({
        componentDidMount: function () {
            let toDetail = r.findDOMNode(this.refs.toDetail);
            let taskId = this.props.taskId;
            let title = '',
                status = '';
            
            if (TYPE == CONFIRM) {
                title = '任务确认';
                status = '01';
            } else if (TYPE == FEEDBACK) {
                title = '任务反馈';
                status = '02';
            } else if (TYPE == CHECK) {
                title = '任务审核';
                status = '03';
            } else if (TYPE == BACK) {
                title = '任务撤回';
                status = '05';
            } else if (TYPE == COMPLETE) {
                title = '已完成';
                status = '04';
            } else if (TYPE == DISPATCH) {
                title = '我派遣的';
                status = '00';
            } else if (TYPE == HELP) {
                title = '协办任务';
                status = '06';
            }
            let type = TYPE == DISPATCH && this.props.info.status == '01' ? DELETE : TYPE; //01表示确认之前阶段
            
            let url = 'daily-work-detail.html?type=' + type + '&status=' + status + '&taskId=' + taskId;
            toDetail.addEventListener('tap', function () {
                doAction(url, title);
            })
        },
        render: function () {
            
            let info = this.props.info,
                setInfo = {
                    btnName: ' ',
                    time: lf.utils.format(info.createTime, 'yyyy-MM-dd hh:mm'),
                    endTime: lf.utils.format(info.endTime, 'yyyy-MM-dd hh:mm'),
                    endTimeReal: lf.utils.format(info.endTimeReal, 'yyyy-MM-dd hh:mm'),
                    name: info.creatorName
                }
            
            if (TYPE == CONFIRM) {
                setInfo.btnName = '确认';
            } else if (TYPE == FEEDBACK) {
                setInfo.btnName = '反馈';
            } else if (TYPE == CHECK) {
                setInfo.btnName = '审核';
            } else if (TYPE == BACK) {
                setInfo.btnName = '撤回';
            } else if (TYPE == COMPLETE) {
                setInfo.btnName = '查看';
            } else if (TYPE == DISPATCH) {
                setInfo.btnName = info.status == '01' ?
                    '删除' : '查看';
            } else if (TYPE == HELP) {
                setInfo.btnName = '协办';
            }
            
            return (
                <div ref='toDetail'>
                    <li className="mui-table-view-cell">
                        <a className="flex-box-row " href="javascript:;">
                            <div className="item flex-box-col">
                                <p className="text-dot">{info.title}</p>
                                <p className="red text-dot">{setInfo.name}</p>
                            </div>
                            <div className="item flex-box-col">
                                <p className="gray small">{'开始时间: ' + setInfo.time}</p>
                                <p className="gray small">{TYPE == COMPLETE ?
                                '实际完成时间: ' + setInfo.endTimeReal :
                                '截止日期: ' + setInfo.endTime}</p>
                            </div>
                        </a>
                    </li>
                    <div>
                        <div className="btn-box">
                            <p data-type="detail" className={
                            "mui-btn mui-btn-green "+
                            (TYPE == DISPATCH && info.status == '01' ? 'redBg' : ' ')
                            }>
                                {setInfo.btnName}
                            </p>
                        </div>
                        <div className="split-line"></div>
                    </div>
                </div>
            )
        }
    })
    
    let Root = r.createClass({
        getInitialState: function () {
            return ({
                list: [],
                headerCounts: [0, 0, 0],
                // headerCounts: [0, 0, 0, 0],
                noData: '',
                taskType: '',
            })
            
        },
        
        getList: function (user, page, shouldAppend) {
            
            if (!page) page = 1;
            
            let me = this,
                taskType = '',
                api = lf.api.worktable.taskList;
            if (TYPE == DISPATCH) {
                taskType = '00';
            } else if (TYPE == CONFIRM) {
                taskType = '01';
            } else if (TYPE == FEEDBACK) {
                taskType = '02';
            } else if (TYPE == CHECK) {
                taskType = '03';
            } else if (TYPE == COMPLETE) {
                taskType = '04';
            } else if (TYPE == BACK) {
                taskType = '05';
            } else if (TYPE == HELP) {
                taskType = '06';
            }
            
            ajax({
                beforeSend() {
                    lf.appJs.doLoading(true);
                },
                type: "POST",
                data: {
                    staffId: user.id,
                    taskType: taskType,
                    page: page,
                },
                success: function (data) {
                    if (data.code == '200') {
                        me.setList(data, shouldAppend);
                        lf.appJs.doLoading(false);
                        
                        if (taskType == '04') {
                            
                            let monthNum = 0,
                                weekNum = 0,
                                markNum = 0,
                                allNum = 0;
                            
                            allNum = data.dataList.length;
                            
                            $.each(data.dataList, function () {
                                
                                let now = new Date().getTime();  //当前时间
                                let endTime = this.endTimeReal;   //结束时间
                                // let endTime = this.endTime;   //结束时间
                                
                                let timeLag = now - endTime; //时间差
                                
                                let date = Math.floor(timeLag / (24 * 3600 * 1000)); //相差天数
                                
                                //计算出相差30天
                                if (date <= 30)
                                    monthNum += 1;
                                //计算出相差7天
                                if (date <= 7)
                                    weekNum += 1;
                            })

                            counts.push(allNum);
                            counts.push(monthNum);
                            counts.push(weekNum);
                            // counts.push(markNum);
                            
                            me.setState({
                                headerCounts: counts,
                                taskType: taskType,
                            });
                        }
                        
                    }
                    else {
                        alert(data.desc);
                    }
                }
            }, api);
            
        },
        setList(data, shouldAppend){
            
            let me = this;
            
            if (data.dataList.length == 0) {
                
             //   me.setState({noData: true})
                
            }
            let resultList = data.dataList,
                maxCount = data.maxCount,
                appendedList;
            // debugAlert(range)TODO 这里接口还没有,暂时模拟
            if (range == MARK) {
                resultList = [];
            }
            if (range == MONTH || range == WEEK) {
                let newResultList = [];
                $.each(resultList, function () {
                    
                    let now = new Date().getTime(); //获取当前时间
                    
                    let endTime = this.endTimeReal;   //结束时间
                    // let endTime = this.endTime;   //结束时间
                    
                    let timeLag = now - endTime; //时间差
                    
                    let date = Math.floor(timeLag / (24 * 3600 * 1000)); //相差天数
                    
                    //计算出相差30天
                    if (date <= 30 && range == MONTH)
                        newResultList.push(this);
                    //计算出相差7天
                    if (date <= 7 && range == WEEK)
                        newResultList.push(this);
                })
                resultList = newResultList;
            }
            
            if (shouldAppend) {
                
                appendedList = me.state.list;
                $.each(resultList, function (i, item) {
                    appendedList.push(item);
                });
                
                mui('#pullrefresh')
                .pullRefresh()
                .endPullupToRefresh((appendedList.length == maxCount)); //refresh completed
                
                me.setState({
                    list: appendedList,
                    noData: false
                });
                
            } else {
                me.setState({
                    list: resultList,
                });
            }
            
        },
        componentWillMount: function () {
            let user = this.props.user;
            
            // lf.appJs.refresh((user) => this.getList(user)); //noticeid错位一条,故暂时改成window.reload
            lf.appJs.refresh();
            
            this.getList(user);
        },
        render: function () {
            return (
                <div className="daily-work-list container">
                    <Header getList={this.getList} user={this.props.user} counts={this.state.headerCounts}
                            taskType={this.state.taskType}
                    />
                    <WorkList info={this.state.list} user={this.props.user} noData={this.state.noData}/>
                </div>
            )
        },
        componentWillReceiveProps: function (nextProps) {
            let page = nextProps.page,
                user = nextProps.user;
            this.getList(user, page, true)
        }
    });
    
    let PullRefreshCon = React.createClass({
        getInitialState: function () {
            return {
                page: 1,
            }
        },
        pullupFn: function () {
            let newPage = ++this.state.page;
            this.setState({page: newPage});
        },
        render: function () {
            let me = this;
            return <PullRefresh pullupFn={me.pullupFn}
                                data={ <Root page={me.state.page}
                                            user={me.props.user}/>
                                     }/>;
        }
    });
    
    lf.appJs.getUser(function (user) {
        r.render(
            <PullRefreshCon user={user}/>,
            document.getElementById('root'), function () {
                $('#root').css('background', 'none');
                
            }
        )
    })
    
})(liefeng, React);
